package com.leff.cards.ui.util;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.leff.cards.R;
import com.leff.cards.data.AbstractCard;

public class CardListAdapter extends BaseAdapter {

	private Context mContext;
	private int[] mSelections;
	private ArrayList<AbstractCard> mCards;
	
	public CardListAdapter(Context C) {
		this(C, new ArrayList<AbstractCard>(), 0);
	}
	public CardListAdapter(Context C, ArrayList<AbstractCard> cards, int selectable) {
		
		mContext = C;
		
		mSelections = new int[selectable];
		resetSelections();
		
		setCards(cards);
	}
	
	public void setCards(ArrayList<AbstractCard> cards) {
		mCards = cards;
		this.notifyDataSetChanged();
	}
	
	public boolean select(int index, int cardId) {
		for(int i = 0; i < mSelections.length; i++) {
			if(mSelections[i] == cardId) {
				return false;
			}
		}
		mSelections[index] = cardId;
		this.notifyDataSetChanged();
		
		return true;
	}
	public void unselect(int index) {
		mSelections[index] = -1;
		this.notifyDataSetChanged();
	}
	public void resetSelections() {
		for(int i = 0; i < mSelections.length; i++) {
			mSelections[i] = -1;
		}
		this.notifyDataSetChanged();
	}
	
	@Override
	public int getCount() {
		return mCards.size();
	}

	@Override
	public Object getItem(int position) {
		return mCards.get(position);
	}

	@Override
	public long getItemId(int position) {
		return mCards.get(position).getId();
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		
		View V = convertView;
		AbstractCard card = mCards.get(position);
		
		if(V == null) {
			V = LayoutInflater.from(mContext).inflate(R.layout.response_card_view, null);
		}
		
		TextView text = (TextView)V.findViewById(R.id.card_text);
		text.setTextColor(Color.BLACK);
		for(int i = 0; i < mSelections.length; i++) {
			if(mSelections[i] == card.getId()) {
				text.setTextColor(Color.GREEN);
				break;
			}
		}
		
		text.setText(card.getText());
		
		return V;
	}
}
